package com.itheima.web.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.Product;
import com.itheima.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

import static oracle.net.aso.C00.n;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private IProductService productService;

    /**
     * 分页查询，查询所有产品信息
     *
     * @param pageNum  当前页
     * @param pageSize 每页显示条数
     * @return
     */
    @RequestMapping("/findAllProduct")
    public ModelAndView findAllProduct(
            //设置参数，默认当前页为第一页，每页显示数量为3条
            @RequestParam(name = "pageNum", required = true, defaultValue = "1") Integer pageNum,
            @RequestParam(name = "pageSize", required = true, defaultValue = "3") Integer pageSize
    ) {
        List<Product> productList = productService.findAllProduct(pageNum, pageSize);
        //使用pageInfo对象将分页信息传递到页面
        PageInfo<Product> pageInfo = new PageInfo<Product>(productList);

        ModelAndView mav = new ModelAndView();
        mav.addObject("product", pageInfo);
        mav.setViewName("product-list");
        return mav;
    }

    /**
     * 添加新产品信息
     *
     * @param product
     * @return
     */
    @RequestMapping("/insertProduct")
    public String insertProduct(Product product) {
        productService.insertProduct(product);
        return "redirect:/product/findAllProduct";
    }


    /**
     * 根据id删除产品信息
     *
     * @param ids
     * @return
     */
    @RequestMapping("/deleteProduct")
    public String deleteProduct(String[] ids) {
        if (ids == null || ids.length == 0) {
            return "forward:/product/findAllProduct";
        }
        for (String id : ids) {
            productService.deleteProduct(id);
        }
        return "forward:/product/findAllProduct";
    }


}
